﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Text;

namespace MdflCommonUtils {
    public class AppConfigUtil {
        /// <summary>
        /// 获取appSetting中对应key的value 如为空或不存在该key则返回默认值
        /// </summary>
        /// <param name="key"></param>
        /// <param name="defaultValue">默认值</param>
        /// <returns></returns>
        public static string GetAppConfig(string key, object defaultValue) {
            string v = ConfigurationManager.AppSettings[key];
            if (v == null || v.Length == 0) {
                return defaultValue == null ? "" : defaultValue.ToString();
            } else {
                return v;
            }
        }

        /// <summary>
        /// 获取appSetting中对应key的value 如为空或不存在该key则返回String.Empty
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string GetAppConfig(string key) {
            return GetAppConfig(key, String.Empty);
        }

        /// <summary>
        /// 判断appSetting中是否存在该配置
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static bool ContainsAppConfig(string key) {
            return ConfigurationManager.AppSettings[key] != null;
        }

        /// <summary>
        /// 保存或更新键值对到appSetting
        /// </summary>
        /// <param name="keyValuePairs"></param>
        public static void SaveAppConfig(Dictionary<string, string> keyValuePairs) {
            //当前应用程序的配置文件
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            if (config == null) {
                return;
            }
            AppSettingsSection appSettings = config.AppSettings;
            foreach (KeyValuePair<string, string> pair in keyValuePairs) {
                if (ContainsAppConfig(pair.Key)) {
                    appSettings.Settings[pair.Key].Value = pair.Value;
                } else {
                    appSettings.Settings.Add(pair.Key, pair.Value);
                }
            }
            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("appSettings");
        }
    }
}
